package com.zzm.validate.web.nutz;

import org.nutz.lang.Strings;
import org.nutz.mvc.ActionContext;
import org.nutz.mvc.ActionInfo;
import org.nutz.mvc.NutConfig;
import org.nutz.mvc.impl.processor.AbstractProcessor;
import org.nutz.mvc.view.JspView;

import com.zzm.validate.web.FormValidator;
import com.zzm.validate.web.HttpServletRequestMapAdapter;
import com.zzm.validate.web.ValidateConfig;

public class ValidateProcessor extends AbstractProcessor {
	
	private String failView;
	private String msgKey;
	private boolean validate;
	
	private FormValidator validator;
	

	@Override
	public void init(NutConfig config, ActionInfo ai) throws Throwable {
		super.init(config, ai);
		validate = config.getMainModule().isAnnotationPresent(Validation.class);
		if(validate) {
			failView = ai.getFailView();
			Validation valid = config.getMainModule().getAnnotation(Validation.class);
			String [] configFiles = valid.configFile();
			String bundleName = valid.bundleName();
			msgKey = valid.msgKey();
			ValidateConfig vConfig = new ValidateConfig();
			if(configFiles != null) {
				vConfig.addConfigFile(configFiles);
			}
			if(!Strings.isBlank(bundleName)) {
				vConfig.setBundle(bundleName);
			}
			validator = vConfig.buildFormValidator();
		}
	}

	@Override
	public void process(ActionContext ac) throws Throwable {
		if(!validate) {
			doNext(ac);
			return;
		}
		String path = ac.getPath();
		Object bean = new HttpServletRequestMapAdapter(ac.getRequest());
		Object messages = validator.validate(path, bean, null);
		if(null == messages) {
			doNext(ac);
		}
		else {
			ac.getRequest().setAttribute(msgKey, messages);
			new JspView(failView).render(ac.getRequest(), ac.getResponse(), null);
		}
	}
	

}
